package com.pointcircle.estate.server.framework.repository;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.pointcircle.core.IRepository;
import com.pointcircle.core.entity.User;
import com.pointcircle.estate.server.framework.entity.CheckQualityCc;
import com.pointcircle.estate.server.framework.entity.CheckQualityProblem;

@Repository
public interface CheckQualityCcRepository extends IRepository<CheckQualityCc, String> {

	List<CheckQualityCc> findByCheckQualityProblem(CheckQualityProblem checkQualityProblem);
	
	@Query("select o from CheckQualityCc o where o.cc = :cc and DATE(o.checkQualityProblem.registDate) > DATE(:showDate)")
	List<CheckQualityCc> findByCcAndDate(@Param("cc") User cc, @Param("showDate") Date newDateToShow);
	
	@Query(value = "select t.cc from tb_checkquality_cc t " + 
			"where t.checkquality_problem_id = ?1 ", nativeQuery = true)
	List<String> findCcIdsByCheckQualityProblemId(String checkQualityProblemId);
	
	default //@Query("select o from CheckQualityCc o where o.checkQualityProblem in :checkQualityProblems")
	List<CheckQualityCc> findByCheckQualityProblemIn(List<CheckQualityProblem> checkQualityProblems){
		if(CollectionUtils.isEmpty(checkQualityProblems)) {
			return new LinkedList<CheckQualityCc>();
		}
		return this.findAll(new Specification<CheckQualityCc>() {
			private static final long serialVersionUID = 3804728714098608584L;

			@Override
			public Predicate toPredicate(Root<CheckQualityCc> root, CriteriaQuery<?> query,
				CriteriaBuilder cb) {
				query.where(
					root.get("checkQualityProblem").in(checkQualityProblems)
				);
				return query.getRestriction();
			}
			
		});
	}
}
